package com.gsafety.devops.controller;
import com.gsafety.devops.entity.PortScanEntity;
import com.gsafety.devops.entity.UrlMonitorEntity;
import com.gsafety.devops.service.UrlMonitorServiceI;
import com.gsafety.devops.util.PortScanner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import org.jeecgframework.core.util.ExceptionUtil;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**   
 * @Title: Controller  
 * @Description: URL监控
 * @author onlineGenerator
 * @date 2018-10-22 17:21:58
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/urlMonitorController")
public class UrlMonitorController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(UrlMonitorController.class);

	@Autowired
	private UrlMonitorServiceI urlMonitorService;
	@Autowired
	private SystemService systemService;
	


	/**
	 * URL监控列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/gsafety/devops/urlMonitorList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(UrlMonitorEntity urlMonitor,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		//更新URL状态
		updateUrlStatus();
		
		
		CriteriaQuery cq = new CriteriaQuery(UrlMonitorEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, urlMonitor, request.getParameterMap());
		try{
		//自定义追加查询条件
		
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.urlMonitorService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	private void updateUrlStatus() {
		List<UrlMonitorEntity> urlList = systemService.getList(UrlMonitorEntity.class);
		for (UrlMonitorEntity url : urlList) {
			try {
				int result = checkUrl(url.getUrl());
				url.setStatus(String.valueOf(result));
				url.setCheckTime(new Date());
			} catch (Exception e) {
				url.setStatus("error");
			}
			systemService.updateEntitie(url);
		}
	}
	
	
	public static int checkUrl(String address) throws Exception {
		int status = 404;
		try {
			URL urlObj = new URL(address);
			HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
			oc.setUseCaches(false);
			oc.setConnectTimeout(1000); // 设置超时时间
			status = oc.getResponseCode();// 请求状态
			if (200 == status) {
				return status;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return status;
	}
	
	/**
	 * 删除URL监控
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(UrlMonitorEntity urlMonitor, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		urlMonitor = systemService.getEntity(UrlMonitorEntity.class, urlMonitor.getId());
		message = "URL监控删除成功";
		try{
			urlMonitorService.delete(urlMonitor);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "URL监控删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除URL监控
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "URL监控删除成功";
		try{
			for(String id:ids.split(",")){
				UrlMonitorEntity urlMonitor = systemService.getEntity(UrlMonitorEntity.class, 
				id
				);
				urlMonitorService.delete(urlMonitor);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "URL监控删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加URL监控
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(UrlMonitorEntity urlMonitor, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "URL监控添加成功";
		try{
			urlMonitorService.save(urlMonitor);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "URL监控添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新URL监控
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(UrlMonitorEntity urlMonitor, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "URL监控更新成功";
		UrlMonitorEntity t = urlMonitorService.get(UrlMonitorEntity.class, urlMonitor.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(urlMonitor, t);
			urlMonitorService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "URL监控更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * URL监控新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(UrlMonitorEntity urlMonitor, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(urlMonitor.getId())) {
			urlMonitor = urlMonitorService.getEntity(UrlMonitorEntity.class, urlMonitor.getId());
			req.setAttribute("urlMonitor", urlMonitor);
		}
		return new ModelAndView("com/gsafety/devops/urlMonitor-add");
	}
	/**
	 * URL监控编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(UrlMonitorEntity urlMonitor, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(urlMonitor.getId())) {
			urlMonitor = urlMonitorService.getEntity(UrlMonitorEntity.class, urlMonitor.getId());
			req.setAttribute("urlMonitor", urlMonitor);
		}
		return new ModelAndView("com/gsafety/devops/urlMonitor-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","urlMonitorController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(UrlMonitorEntity urlMonitor,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(UrlMonitorEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, urlMonitor, request.getParameterMap());
		List<UrlMonitorEntity> urlMonitors = this.urlMonitorService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"URL监控");
		modelMap.put(NormalExcelConstants.CLASS,UrlMonitorEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("URL监控列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,urlMonitors);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(UrlMonitorEntity urlMonitor,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"URL监控");
    	modelMap.put(NormalExcelConstants.CLASS,UrlMonitorEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("URL监控列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<UrlMonitorEntity> listUrlMonitorEntitys = ExcelImportUtil.importExcel(file.getInputStream(),UrlMonitorEntity.class,params);
				for (UrlMonitorEntity urlMonitor : listUrlMonitorEntitys) {
					urlMonitorService.save(urlMonitor);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	
}
